package com.eshop.tools.utils;

import java.util.Iterator;
import com.alipay.api.AlipayApiException;
import java.util.Map;
import com.alipay.api.internal.util.AlipaySignature;
import java.util.HashMap;
import com.eshop.tools.domain.AlipayConfig;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.text.SimpleDateFormat;
import org.springframework.stereotype.Component;

@Component
public class AlipayUtils
{
    public String getOrderCode() {
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        final int a = (int)(Math.random() * 9000.0) + 1000;
        System.out.println(a);
        final Date date = new Date();
        final String str = sdf.format(date);
        final String[] split = str.split("-");
        final String s = split[0] + split[1] + split[2];
        final String[] split2 = s.split(" ");
        final String s2 = split2[0] + split2[1];
        final String[] split3 = s2.split(":");
        return split3[0] + split3[1] + split3[2] + a;
    }
    
    public boolean rsaCheck(final HttpServletRequest request, final AlipayConfig alipay) {
        final Map<String, String> params = new HashMap<String, String>(1);
        final Map requestParams = request.getParameterMap();
        for (final Object o : requestParams.keySet()) {
            final String name = (String)o;
            final String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; ++i) {
                valueStr = ((i == values.length - 1) ? (valueStr + values[i]) : (valueStr + values[i] + ","));
            }
            params.put(name, valueStr);
        }
        try {
            return AlipaySignature.rsaCheckV1((Map)params, alipay.getPublicKey(), alipay.getCharset(), alipay.getSignType());
        }
        catch (AlipayApiException e) {
            return false;
        }
    }
}
